package cn.uyunsky.platform.controller;

import cn.uyunsky.platform.BeanFactoryUtil;
import cn.uyunsky.platform.data.GridPageVO;
import cn.uyunsky.platform.data.UData;
import cn.uyunsky.platform.data.UDataTool;
import cn.uyunsky.platform.data.UHead;
import cn.uyunsky.platform.exception.PLException;
import cn.uyunsky.platform.service.ServiceExecute;
import cn.uyunsky.platform.servlet.ServletUtil;
import cn.uyunsky.platform.util.PL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.Map;

/**
 * 表格查询公共controller;界面输入一个queryParameter的json字符串;此处直接解析后调用服务
 */
@Controller
public class GridQueryController {

    static Logger logger = LoggerFactory.getLogger(GridQueryController.class);

    private ServiceExecute serviceExecute;

    public void setServiceExecute(ServiceExecute serviceExecute) {
        this.serviceExecute = serviceExecute;
    }

    @RequestMapping(value = "/gridQuery")
    public ModelAndView login(
            @RequestParam("service") String service,
            @RequestParam("queryParameter") String queryParameter,
            Integer start,
            Integer limit,
            String sortBy,
            String sortDir,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        //URL中存在中文时需要转码; $.param处理了转码问题,不用特殊处理
        //queryParameter = new String(queryParameter.getBytes("ISO-8859-1"),"UTF-8");
        if (logger.isDebugEnabled())
            logger.debug("Grid查询开始,服务[{}],参数[{}]", service, queryParameter);

        Map body = PL.JSON.fromJSON(queryParameter);
        if (start != null)
            body.put("start", start);

        if (limit != null)
            body.put("limit", limit);

        if (sortBy != null)
            body.put("sortBy", sortBy);

        if (sortDir != null)
            body.put("sortDir", sortDir);

        UHead head = new UHead();
        head.setService(service);
        setUserInfo(request, head);

        // 执行服务
        UData data = new UData();
        data.setHead(head);
        data.setBody(body);
        data.setJson(queryParameter);

        if (logger.isDebugEnabled())
            logger.debug("请求数据为:" + data);

        try {
            UData resData = serviceExecute.execute(service, data);

            if (logger.isDebugEnabled())
                logger.debug("响应数据为:" + resData);

            GridPageVO vo = new GridPageVO();
            boolean hasresult = false;
            Map<String, Object> resBody = resData.getBody();
            for (Iterator<Object> it = resBody.values().iterator(); it.hasNext(); ) {
                Object v = it.next();
                if (v instanceof GridPageVO) {
                    //获取第一个GridPageVO对象作为Grid返回值
                    vo = (GridPageVO) v;
                    hasresult = true;
                    break;
                }
            }

            if (!hasresult) {
                throw new PLException("system.grid_query_error");
            }

            ServletUtil.wirteJSONObj(vo, response);
        } catch (PLException e) {
            logger.error("GridQuery执行业务错误", e);
            GridPageVO vo = new GridPageVO();
            vo.setMsg(e.getMessage());
            ServletUtil.wirteJSONObj(vo, response);
        } catch (Exception e) {
            logger.error("GridQuery服务执行异常", e);
            GridPageVO vo = new GridPageVO();
            vo.setMsg(UDataTool.ERROR_MSG);
            ServletUtil.wirteJSONObj(vo, response);
        }
        return null;
    }

    private void setUserInfo(HttpServletRequest req, UHead head) {
        head.setUserid(ControllerTool.getUseridBySession(req.getSession()));
    }


}
